using Microsoft.AspNetCore.Mvc;
using TMS.Application.Common.Interface;
using TMS.Application.RequestDto;
using TMS.Domain.Entity;

namespace TMS.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UniLoginController : ControllerBase
    {
        private readonly IRepository<Students> _students;
        private readonly IRepository<UniLogin> _uniLogin;


        public UniLoginController(IRepository<Students> students, IRepository<UniLogin> uniLogin)
        {
            _students = students;
            _uniLogin = uniLogin;
        }
        [HttpPost("/loginlist")]
        public async Task<object> LoginList(UniLoginDto uniLoginDto)
        {
            //根据传入的学号来查找

            var uniTable = _uniLogin.Table.FirstOrDefault(x => x.Openid == uniLoginDto.OpenId);

            if (uniTable != null)
            {
                var s = _students.Table.FirstOrDefault(x => x.StudentId == uniTable.UserId);
                if (s != null)
                {
                    return new
                    {
                        code=200,
                        data=s,
                        msg="open登录成功"
                        
                    };
                }
                else
                {
                    var u = _uniLogin.Table.FirstOrDefault(x => x.Openid == uniLoginDto.OpenId);
                    await _uniLogin.DeleteAsync(u);
                    return new { 
                        code=400,
                        data="",
                        msg="学号不存在,请重新登录"
                    };
                }
            }
            else
            {
                var unilogin = new UniLogin
                {
                    UserId = uniLoginDto.UserId,
                    Openid = uniLoginDto.OpenId
                };
                var s = _students.Table.FirstOrDefault(x => x.StudentId == uniLoginDto.UserId);
                if (s != null)
                {
                    await _uniLogin.AddAsync(unilogin);

                    return new
                    {
                        code = 200,
                        data = s,
                        msg = "登录成功",
                    };
                }
                else
                {
                    return new
                    {
                        code = 401,
                        msg = "用户不存在",
                        data = ""
                    };
                }

            }

        }
        [HttpDelete("/loginDel")]
        public async Task<object> LoginDel()
        {
            //根据传入的学号来查找


            //var uniTable = _uniLogin.Table.FirstOrDefault(x => x.UserId == uniLoginDto.StudentId);
            var d = _uniLogin.Table;
            await _uniLogin.DeleteBulkAsync(d);



            return new
            {
                code = 200,
                data = "",
                msg = "删除成功",
            };
        }
    }
}